package org.springblade.modules.admin.task.erp;

import cn.hutool.core.date.DateUtil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.flow.repair.parts.service.IPartsService;
import org.springblade.modules.admin.dto.erp.PartnerCloudTableDeleteBatchDTO;
import org.springblade.modules.admin.dto.erp.PartnerCloudTableItemDTO;
import org.springblade.modules.admin.dto.erp.PartnerCloudTableSaveOrUpdateDTO;
import org.springblade.modules.admin.dto.erp.PartnerCloudTableSearchFullDTO;
import org.springblade.modules.admin.dto.erp.serivce.PartnerCloudPartsListDTO;
import org.springblade.modules.admin.enums.erp.ERPTableEnum;
import org.springblade.modules.admin.enums.erp.options.BuildingMessageTypeEnum;
import org.springblade.modules.admin.enums.erp.tables.BuildingMessageEnum;
import org.springblade.modules.admin.enums.erp.tables.PartTaskEnum;
import org.springblade.modules.admin.service.BuildingService;
import org.springblade.modules.admin.service.IPartsInfoService;
import org.springblade.modules.admin.service.erp.IPartnerCloudSpaceTableService;
import org.springblade.modules.admin.vo.erp.service.BuildingMessageVO;
import org.springblade.modules.admin.vo.erp.tables.PartnerCloudTableItemListVO;
import org.springblade.modules.admin.vo.erp.tables.PartnerCloudTableItemVO;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: Sharry
 * @createTime: 2024-12-31 18:19
 * @version: Version-1.0
 */
@Component
@Slf4j
public class PartnerCloudBuildingMessageJob {

	@Resource
	private BuildingService buildingService;

	@Resource
	private IPartnerCloudSpaceTableService partnerTableService;

	@Resource
	private IPartsInfoService partsInfoService;

	/**
	 * 定时任务：每天上午4：00
	 */
	@XxlJob(value = "partnerCloudBuildingMessageJob")
	public void partnerCloudBuildingMessagePurchaseJob() {
		XxlJobHelper.handleSuccess("伙伴云项目信息同步[执行]开始");
		try{
			isProdEnv();
			String tableId = ERPTableEnum.BUILDING_MESSAGE.getTableId();
			// 1. 查询数据
			List<BuildingMessageVO> buildingMessageVOList = buildingService.selectBuildingMessageList();
			// 2. 处理数据/数据封装
			PartnerCloudTableSaveOrUpdateDTO saveOrUpdateDTO = new PartnerCloudTableSaveOrUpdateDTO();
			saveOrUpdateDTO.setTable_id(tableId);
			List<String> updateFields = new ArrayList<>();
			updateFields.add(BuildingMessageEnum.BUILDING_ID.getFieldId());
			saveOrUpdateDTO.setUpdate_by_fields(updateFields);
			List<PartnerCloudTableItemDTO> items = new ArrayList<>();

			// 处理数据并封装
			if(Func.isNotEmpty(buildingMessageVOList)){
				for(BuildingMessageVO buildingMessageVO : buildingMessageVOList){
					PartnerCloudTableItemDTO item = new PartnerCloudTableItemDTO();
					Map<String,Object> fields = new HashMap<>(10);
					fields.put(BuildingMessageEnum.BUILDING_ID.getFieldId(), buildingMessageVO.getBuildingId());
					fields.put(BuildingMessageEnum.BUILDING_NAME.getFieldId(), buildingMessageVO.getBuildingName());
					fields.put(BuildingMessageEnum.USE_UNIT.getFieldId(), buildingMessageVO.getUserUnitName());
					fields.put(BuildingMessageEnum.CONTACT_PERSON.getFieldId(), buildingMessageVO.getContactsName());
					fields.put(BuildingMessageEnum.PHONE.getFieldId(), buildingMessageVO.getPhone());
					fields.put(BuildingMessageEnum.ADDRESS.getFieldId(), buildingMessageVO.getAddress());
					String type = buildingMessageVO.getBuildingType();
					if(!Func.isNull(type)){
						List<String> typeList = new ArrayList<>();
						String idByDictKey = BuildingMessageTypeEnum.getIdByDictKey(type);
						typeList.add(idByDictKey);
						fields.put(BuildingMessageEnum.TYPE.getFieldId(),typeList);
					}
					item.setFields(fields);
					items.add(item);
				}
			}
			saveOrUpdateDTO.setItems(items);
			partnerTableService.saveOrUpdateByFields(saveOrUpdateDTO);
			XxlJobHelper.handleSuccess("伙伴云项目信息同步-[执行]成功");
		}catch (Exception e){
			XxlJobHelper.handleSuccess("伙伴云项目信息同步[执行]失败"+e);
		}

	}

	/**
	 * 定时任务：每天上午3:00
	 */
	@XxlJob(value = "partnerCloudPartsTaskListJob")
	public void partnerCloudPartsTaskListJob() {
		XxlJobHelper.handleSuccess("伙伴云配件任务同步[执行]开始");
		try{
			String tableId = ERPTableEnum.PART_TASK_LIST.getTableId();
			// 1. 查询数据、处理数据
			List<PartnerCloudPartsListDTO> taskListDTO = partsInfoService.selectPartsList();
			// 2. 处理数据/数据封装
			PartnerCloudTableSaveOrUpdateDTO saveOrUpdateDTO = new PartnerCloudTableSaveOrUpdateDTO();
			saveOrUpdateDTO.setTable_id(tableId);
			List<String> updateFields = new ArrayList<>();
			updateFields.add(PartTaskEnum.PLAN_ID.getFieldId());
			saveOrUpdateDTO.setUpdate_by_fields(updateFields);
			List<PartnerCloudTableItemDTO> items = new ArrayList<>();

			// 处理数据并封装
			if(Func.isNotEmpty(taskListDTO)){
				for(PartnerCloudPartsListDTO dto : taskListDTO){
					PartnerCloudTableItemDTO item = new PartnerCloudTableItemDTO();
					Map<String,Object> fields = new HashMap<>(10);
					fields.put(PartTaskEnum.PLAN_ID.getFieldId(), dto.getPlanId());
					fields.put(PartTaskEnum.PLAN_STATUS.getFieldId(), dto.getPlanStatus());
					fields.put(PartTaskEnum.PROCESS_STATUS.getFieldId(), dto.getProcessStatus());
                    fields.put(PartTaskEnum.PARTS_MODEL.getFieldId(), dto.getPartsModel());
					fields.put(PartTaskEnum.PART_NAME.getFieldId(), dto.getPartName());
					fields.put(PartTaskEnum.APPLY_USER.getFieldId(),dto.getApplyUser());
					fields.put(PartTaskEnum.RELATION_PLAN_ID.getFieldId(),dto.getRelationPlanId());
					fields.put(PartTaskEnum.BUILDING_NAME.getFieldId(),dto.getBuildingName());
					fields.put(PartTaskEnum.ELEVATOR_ADDRESS.getFieldId(),dto.getElevatorAddress());
					fields.put(PartTaskEnum.DETAIL_LINK.getFieldId(),dto.getDetailLink());
					fields.put(PartTaskEnum.ELEVATOR_STATUS.getFieldId(),dto.getElevatorStatus());
					fields.put(PartTaskEnum.EMERGENCY.getFieldId(),dto.getEmergency());
					fields.put(PartTaskEnum.EXECUTORS.getFieldId(),dto.getExecutors());
					fields.put(PartTaskEnum.PLAN_TYPE.getFieldId(),dto.getPlanType());
					fields.put(PartTaskEnum.PARTS_NUM.getFieldId(),dto.getPartsNum());
					fields.put(PartTaskEnum.EXECUTORS.getFieldId(),dto.getExecutors());
					fields.put(PartTaskEnum.PLAN_EXECUTORS.getFieldId(),dto.getPlanExecutors());
					/**
					 * 时间处理
					 */
					if(Func.isNotEmpty(dto.getApplyTime())) {
						fields.put(PartTaskEnum.APPLY_TIME.getFieldId(), DateUtil.format(dto.getApplyTime(), "yyyy-MM-dd HH:mm:ss"));
					}
					if(Func.isNotEmpty(dto.getRelationPlanFinishTime())){
						fields.put(PartTaskEnum.RELATION_PLAN_FINISH_TIME.getFieldId(), DateUtil.format(dto.getRelationPlanFinishTime(), "yyyy-MM-dd HH:mm:ss"));
					}
					item.setFields(fields);
					items.add(item);
				}
			}
			saveOrUpdateDTO.setItems(items);
			partnerTableService.saveOrUpdateByFields(saveOrUpdateDTO);
			XxlJobHelper.handleSuccess("伙伴云配件任务同步-[执行]成功");
		}catch (Exception e){
			XxlJobHelper.handleSuccess("伙伴云配件任务同步[执行]失败"+e);
		}

	}

	private void isProdEnv(){
		String prodEnv = "prod";
		String activeProfile = System.getProperty("spring.profiles.active");
		log.info("当前环境为：{}", activeProfile);
		if (!prodEnv.equals(activeProfile)){
			throw new ServiceException("非正式环境不能对伙伴云ERP进行操作!");
		}
	}

}
